const express = require("express")
const pool = require("../utils/DBUtils")
var router = express.Router()

router.get("/list", async (req, res) => {
    // let {page,pageSize} = req.query
    // page = page == null ? 1 : page;
    // pageSize = pageSize == null ? 10 : pageSize
    // let params = []
    // let whereSqls = []
    // let whereSqlStr = ""
    // if (whereSqls.length > 0) {
    //     whereSqlStr = " WHERE " + whereSqls.join(" AND ")
    // }

    //  //查分页数据
    //  let searchSql = " SELECT `Stu_id`,`category_id`,`create_time`,`title`,substr(`content`,0,50) AS `content` FROM `blog` " + whereSqlStr + " ORDER BY `create_time` DESC LIMIT ?,? "
    //  // 1 10  2,10    3,5
    //  // 0,10  10,10   10,5
    //  let searchSqlParams = params.concat([(page - 1) * pageSize, pageSize])
 
    //  //查询数据总数
    //  let searchCountSql = " SELECT count(*) AS `count` FROM `stu` " + whereSqlStr;
    //  let searchCountParams = params
 
    //  //分页数据
    //  let searchResult = await pool.async.all(searchSql, searchSqlParams)
    //  let countResult = await pool.async.all(searchCountSql, searchCountParams)
 
    //  console.log(searchSql, countResult)
 
    //  if (searchResult.err == null && countResult.err == null) {
    //      res.send({
    //          code: 200,
    //          msg: "查询成功",
    //          data: {  
    //              page,
    //              pageSize,
    //              rows: searchResult.rows,
    //              count: countResult.rows[0].count
    //          }
    //      })
 
    //  } else {
    //      res.send({
    //          code: 500,
    //          msg: "查询失败",
    //      })
    //  }

    let { result } = await pool.async.query("SELECT * from `stu`")
    res.send({
        msg: "查询成功",
        data: result
    })
})
//查询接口，根据id查询数据
router.get("/search/:id", async (req, res) => {
    let { id } = req.params
    let result = await pool.async.query("SELECT * from stu where `stu_id`=?",[id])
    res.send({
        code: 200,
        msg: "查询成功",
        data: result    
    })
})

// 添加接口
router.post("/add", async (req, res) => {
    let data = req.body
    let result =await pool.async.query("insert into stu(`stu_id`,`stu_name`,`stu_class`) values(?,?,?)", [data.stu_id,data.stu_name,data.stu_class])
    res.send({
        code: 200,
        msg: "添加成功",
        data: result
    })
})
//删除接口，根据id  删除数据
router.delete("/delete/:id",async(req,res)=>{
    let {id} = req.params
    let result = await pool.async.query("delete from stu where `stu_id`=?",[id])
    res.send({
        code:200,
        msg:"删除成功"
    })
})

//修改接口,根据id修改数据
router.put("/update",async(req,res)=>{
    let data = req.body
    let result = await pool.async.query("UPDATE stu SET stu_name=?, stu_class=? WHERE `stu_id`=?",[data.stu_name,data.stu_class,data.stu_id])  
    res.send({
        code: 200,
        msg: "修改成功",
        data: result
    })
})
module.exports = router